package com.cysion.study.ui.login

import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.CompoundButton
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.other._setOnClickListener
import com.cysion.other.color
import com.cysion.other.startActivity_ex
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.constant.BUNDLE_KEY
import com.cysion.study.constant.LOGIN_IN
import com.cysion.study.event.UserEvent
import com.cysion.study.net.ApiClient
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import kotlinx.android.synthetic.main.activity_register.*
import org.greenrobot.eventbus.EventBus

/**
 * Created by chu on 2019-06-29.
 */
class RegisterActivity :BaseActivity(), CompoundButton.OnCheckedChangeListener, View.OnClickListener {

    override fun closeMvp() {
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_register
    }

    var type:String="0"
    override fun initView() {
        whiteTextTheme(color(R.color.main_cl))
        cb_teacher.setOnCheckedChangeListener(this)
        cb_private.setOnCheckedChangeListener(this)
        tvLogin.setOnClickListener(this)
        tv_forget.setOnClickListener(this)
        iv_back.setOnClickListener(this)
        tvNext._setOnClickListener {
            val account = etUsername.text.toString()
            val pwd = etPwd.text.toString()
            etUsername.checkBlank("手机号不能为空") ?: return@_setOnClickListener
            etCode.checkBlank("验证码不能为空") ?: return@_setOnClickListener
            etPwd.checkBlank("密码不能为空") ?: return@_setOnClickListener
            etPwd2.checkBlank("密码不能为空") ?: return@_setOnClickListener

            if (etUsername.text.toString().length < 11 || etPwd.text.length < 6) {
                ShowToast("请输入正确的手机号或6位以上密码")
                return@_setOnClickListener
            }
            if (etPwd.text.toString() != etPwd2.text.toString()) {
                ShowToast("两次输入密码不一致")
                return@_setOnClickListener
            }
            type = "1"

            /*if (cb_teacher.isChecked) {
                type = "0"
            } else if (cb_private.isChecked) {
                type = "1"
            }*/
            //登录类型 1普通员工 2.私教

            if (!cb_agree.isChecked) {
                ShowToast("注册须同意用户协议与隐私政策")
                return@_setOnClickListener
            }
            ACache.get(Box.context).put("teacherType", type)
            //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码
            ApiClient.api.checkCode(etUsername.text.toString().trim(), "0", etCode.text.toString().trim())
                .compose(BaseResponseRx.validateToMain())
                ._subscribe {
                    _onNext {
//                        Alert.close()
                        //验证码校验成功
                        toRegister()
                    }
                    _onError {
//                        Alert.close()
                        val handle = ErrorHandler.handle(it)
                        ShowToast(handle.errorMsg)
                    }
                }
        }
        countTimer = CountTime(60000, 1000)
        tvCode.setOnClickListener(this)
        tv_agree.setOnClickListener(this)
        tv_zc.setOnClickListener(this)
    }

    private fun toRegister() {
        Alert.loading(self)
        //注册类型 0.普通教师 1.私教
        ApiClient.api.registers(
            etUsername.text.toString().trim()
            , type, etPwd.text.toString().trim(), etCode.text.toString().trim()
        ).compose(BaseResponseRx.validateToMain())._subscribe {
            _onNext{
                Alert.close()
                ShowToast("注册成功")
                CLog.i("token=${it.token}")
                ACache.get(Box.context).put("token", it.token)

                finish()
                EventBus.getDefault().post(UserEvent(LOGIN_IN, ""))
            }
            _onError {
                Alert.close()
                val handle = ErrorHandler.handle(it)
                ShowToast(handle.errorMsg)
            }
        }
    }

    private lateinit var countTimer: CountTime
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back->{
                finish()
            }
            ////类型：1、家长端关于介绍；2、教师端关于介绍 3.家长端用户协议 4.家长端隐私政策 5.普教端用户协议 6.普教端隐私政策
            R.id.tv_agree->{
                var bundle = Bundle()
                bundle.putString("type","5")
                UIHelper.jump(self, WebViewActivity::class.java,bundle)
            }
            R.id.tv_zc->{
                var bundle = Bundle()
                bundle.putString("type","6")
                UIHelper.jump(self, WebViewActivity::class.java,bundle)
            }
            R.id.tvCode->{
                etUsername.checkBlank("手机号不能为空") ?: return
                Alert.loading(self)
                //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码
                ApiClient.api.sendCdoe(etUsername.text.toString().trim(),"0").compose(BaseResponseRx.validateToMain())
                    ._subscribe {
                        _onNext {
                            Alert.close()
                            ShowToast("发送成功")
                        }
                        _onError {
                            if (countTimer != null) {
                                countTimer.cancel()
                            }
                            tvCode.isEnabled = true
                            tvCode.text = "获取验证码"
                            Alert.close()
                            val handle=ErrorHandler.handle(it)
                            ShowToast(handle.errorMsg)
                        }
                    }
                countTimer.start()
                tvCode.isEnabled = false
            }
            R.id.tvLogin -> {
                self.startActivity_ex<LoginActivity>()
                finish()
            }
            R.id.tv_forget -> {
                if (countTimer != null) {
                    countTimer.cancel()
                }
                //
                val pageType = "1"
                var bundle = Bundle()
                bundle.putString("pageType", pageType)
                self.startActivity_ex<ForgetPwdActivity>(BUNDLE_KEY,bundle)
            }
        }
    }

    inner class CountTime : CountDownTimer {
        constructor(millisInFuture: Long, countDownInterval: Long) : super(millisInFuture, countDownInterval)
        override fun onFinish() {
            tvCode.isEnabled = true
            tvCode.text = "获取验证码"
        }

        override fun onTick(millisUntilFinished: Long) {
            tvCode.text = "${millisUntilFinished/1000}秒"
        }

    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (buttonView != null) {

            if (buttonView.id == cb_teacher.id) {
                cb_private.isChecked = !isChecked
            } else if (buttonView.id == cb_private.id) {
                cb_teacher.isChecked = !isChecked
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countTimer != null) {
            countTimer.cancel()
        }
    }
}